package com.palm.easy.controller;

import com.palm.easy.anno.Auth;
import com.palm.easy.service.ConfigService;
import com.palm.easy.service.ServerManageService;
import com.palm.easy.util.StringUtil;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;

import java.util.Objects;

@Controller
@Mapping("api")
public class ApiController {
    @Inject
    ConfigService configService;
    @Inject
    ServerManageService manageService;
    private boolean access(Context ctx){
        String token=configService.getConfig("token");
        if(StringUtil.isNotEmpty(token)){
           String tk= ctx.header("token");
           if(StringUtil.isEmpty(tk)){
               tk=ctx.param("token");
           }
           boolean ret = Objects.equals(token,tk);
           if(!ret){
               ctx.status(403);
           }
           return ret;
        }
        return true;
    }
    @Mapping("services")
    public Result services(Context ctx){
        if(!access(ctx)){
            return Result.failure("没有权限");
        }
        return Result.succeed(manageService.foundServices());
    }
    @Mapping("config")
    public Result config(Context ctx){
        if(!access(ctx)){
            return Result.failure("没有权限");
        }
        return Result.succeed(configService.getConfigs());
    }
}
